//
//  BattlingView.m
//  Dispatch
//
//  Created by hyeyeon on 14. 2. 5..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "BattlingView.h"

#define FIRSTSELECT_HIDDEN_X    -(mySize.width/2)
#define FIRSTSELECT_APPEAR_X    0
#define SECONDSELECT_HIDDEN_X   mySize.width
#define SECONDSELECT_APPEAR_X   (mySize.width/2)

#define TIMEOFLOADINGVIEW       3.0f
#define NEXTDELAYTIME           2.0f

@implementation BattlingView
@synthesize responseData, firstIndex, imageURL, itemArray, firstDic, secondDic, toptenArray, totalArray, tenArray, rankingArray, imageTenArray, imageTenDic, currentStarIDs;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = ColorFromRGB(0x413c43);
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
        self.responseData = [NSMutableData data];
        
        tenArray = [[NSMutableArray alloc] init];
        totalArray = [[NSMutableArray alloc] init];
        imageTenArray = [[NSMutableArray alloc] init];
        imageTenDic = [[NSMutableDictionary alloc] init];
        
        [self makeObject:frame];
//        [self makeLoadingView];
//
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)makeObject:(CGRect)frame{
    
    
    //title
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.titleLabel.text = NSLocalizedString(@"starBattle", @"");
    
    //subtitle
    [self setSubTitleIcond:[UIImage imageNamed:@"icon_battle_notice"] andTitle:nil];
    
    float selectOriginY = deviceIphone4 ? 10 : 57;
    
    //vs : first
    firstSelect = [[UIButton alloc] initWithFrame:CGRectMake(FIRSTSELECT_HIDDEN_X,selectOriginY, mySize.width*0.5f, 300)];
    firstSelect.backgroundColor = ColorFromRGB(0x4d4d57);
    [firstSelect setImage:[UIImage imageNamed:@"thumb_default"] forState:UIControlStateNormal];
    [firstSelect addTarget:self action:@selector(firstSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bodyView addSubview:firstSelect];
    
    firstImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, firstSelect.frame.size.width, firstSelect.frame.size.height)];
    [firstSelect addSubview:firstImageView];
    
    UIView *firstTitleBGView = [[UIView alloc] initWithFrame:CGRectMake(0, firstSelect.frame.size.height-25, firstSelect.frame.size.width, 25)];
    firstTitleBGView.backgroundColor = ColorFromRGB(0x2b2b31);
    firstTitleBGView.alpha = 0.8f;
    [firstSelect addSubview:firstTitleBGView];
    
    firstTitle = [[UILabel alloc] initWithFrame:firstTitleBGView.frame];
    firstTitle.backgroundColor = [UIColor clearColor];
    firstTitle.textColor = ColorFromRGB(0xffffff);
    firstTitle.font = [UIFont systemFontOfSize:14];
    firstTitle.textAlignment = NSTextAlignmentCenter;
    [firstSelect addSubview:firstTitle];
    
    selectBtncenterY = firstSelect.center.y;
    
    //vs : second
    secondSelect = [[UIButton alloc] initWithFrame:CGRectMake(SECONDSELECT_HIDDEN_X, firstSelect.frame.origin.y, firstSelect.frame.size.width, 300)];
    secondSelect.backgroundColor = firstSelect.backgroundColor;
    [secondSelect setImage:[UIImage imageNamed:@"thumb_default"] forState:UIControlStateNormal];
    [secondSelect addTarget:self action:@selector(secondSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bodyView addSubview:secondSelect];
    
    secondImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, secondSelect.frame.size.width, secondSelect.frame.size.height)];
    [secondSelect addSubview:secondImageView];
    
    UIView *secondTitleBGView = [[UIView alloc] initWithFrame:firstTitleBGView.frame];
    secondTitleBGView.backgroundColor = ColorFromRGB(0x2b2b31);
    secondTitleBGView.alpha = 0.8f;
    [secondSelect addSubview:secondTitleBGView];
    
    secondTitle = [[UILabel alloc] initWithFrame:secondTitleBGView.frame];
    secondTitle.backgroundColor = [UIColor clearColor];
    secondTitle.textColor = ColorFromRGB(0xffffff);
    secondTitle.font = [UIFont systemFontOfSize:14];
    secondTitle.textAlignment = NSTextAlignmentCenter;
    [secondSelect addSubview:secondTitle];
    
    //icon
    UIImageView *circleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 70, 70)];
    circleImageView.image = [UIImage imageNamed:@"vs_circle"];
    circleImageView.center = CGPointMake(mySize.width*0.5f, firstSelect.center.y);
    [self.bodyView addSubview:circleImageView];
    [self iconAnimation:circleImageView];
    
    firstSelect.hidden = secondSelect.hidden = YES;
    
    //기사보기
    firstNewsButton = [[UIButton alloc] initWithFrame:CGRectMake(0, selectOriginY+firstSelect.frame.size.height+5, 50, 16)];
    [firstNewsButton setImage:[UIImage imageNamed:@"btn_news"] forState:UIControlStateNormal];
    [firstNewsButton addTarget:self action:@selector(firstNewsButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bodyView addSubview:firstNewsButton];
    firstNewsButton.center = CGPointMake(mySize.width*0.25f, firstNewsButton.center.y);
    
    UILabel *firstNewsLabel = [[UILabel alloc] initWithFrame:CGRectMake(7, 0, firstNewsButton.frame.size.width-7, firstNewsButton.frame.size.height)];
    firstNewsLabel.backgroundColor = [UIColor clearColor];
    firstNewsLabel.textColor = ColorFromRGB(0x909090);
    firstNewsLabel.text = NSLocalizedString(@"news", @"");
    firstNewsLabel.font = [UIFont systemFontOfSize:9];
    [firstNewsButton addSubview:firstNewsLabel];
    
    secondNewsButton = [[UIButton alloc] initWithFrame:CGRectMake(0, selectOriginY+firstSelect.frame.size.height+5, 50, 16)];
    [secondNewsButton setImage:[UIImage imageNamed:@"btn_news"] forState:UIControlStateNormal];
    [secondNewsButton addTarget:self action:@selector(secondNewsButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.bodyView addSubview:secondNewsButton];
    secondNewsButton.center = CGPointMake(mySize.width*0.75f, secondNewsButton.center.y);
    
    UILabel *secondNewsLabel = [[UILabel alloc] initWithFrame:CGRectMake(7, 0, secondNewsButton.frame.size.width-7, secondNewsButton.frame.size.height)];
    secondNewsLabel.backgroundColor = [UIColor clearColor];
    secondNewsLabel.textColor = ColorFromRGB(0x909090);
    secondNewsLabel.text = NSLocalizedString(@"news", @"");
    secondNewsLabel.font = [UIFont systemFontOfSize:9];
    [secondNewsButton addSubview:secondNewsLabel];
    
}

-(void)makeWinView{
    
    winView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.bodyView addSubview:winView];
    winView.hidden = YES;
    
    
    winLabel = [[NKLabel alloc] initWithFrame:CGRectZero];
    winLabel.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.5f];
    winLabel.layer.cornerRadius = 3.0f;
    [winView addSubview:winLabel];
    
    loseLabel = [[NKLabel alloc] initWithFrame:CGRectZero];
    loseLabel.backgroundColor = winLabel.backgroundColor;
    loseLabel.layer.cornerRadius = winLabel.layer.cornerRadius;
    [winView addSubview:loseLabel];
    
    winImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    winImageView.image = [UIImage imageNamed:@"icon_win"];
    [winView addSubview:winImageView];
    
}




#pragma mark - 보여지고나서
-(void)didAppear{
//    [self appearSelectButtonAnimation]; //임시
    [self makeWinView];
    [self requestStart];
}

#pragma mark - Activity View
-(void)makeActivityView{
    
    smallLoadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 100)];
    smallLoadingView.backgroundColor = [UIColor clearColor];
    
    activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityView.center = CGPointMake(smallLoadingView.frame.size.width*0.5f, 20);
    [smallLoadingView addSubview:activityView];
    
    UILabel *message = [[UILabel alloc] initWithFrame:CGRectMake(5, activityView.frame.origin.y+activityView.frame.size.height+5, smallLoadingView.frame.size.width-10, 50)];
    message.backgroundColor = [UIColor clearColor];
    message.font = [UIFont systemFontOfSize:10];
    message.numberOfLines = 0;
    message.textColor = ColorFromRGB(0xffffff);
    message.textAlignment = NSTextAlignmentCenter;
    message.text = [NSString stringWithFormat:@"%@\n%@",NSLocalizedString(@"loadingBattle1", @""),NSLocalizedString(@"loadingBattle2", @"")];
//    [message sizeToFit];
//    message.center = CGPointMake(activityView.frame.size.width*0.5f, activityView.frame.origin.y+activityView.frame.size.height+5+(message.frame.size.height*0.5f));
    [smallLoadingView addSubview:message];
    [self.bodyView addSubview:smallLoadingView];
}

-(void)appearSmallLoadingViewOnLeft:(BOOL)yn{
    if (!smallLoadingView) {
        [self makeActivityView];
    }
    [activityView startAnimating];
    

    smallLoadingView.center = yn ? CGPointMake(160*0.5f, selectBtncenterY-50) : CGPointMake(mySize.width-(160*0.5f), selectBtncenterY-50);
}

-(void)removeSmallLoadingView{

    if (smallLoadingView) {
        [activityView stopAnimating];
        
        if ([smallLoadingView superview]) {
            [smallLoadingView removeFromSuperview];
            smallLoadingView = nil;
        }
    }
}


#pragma mark - WIN 수치
-(void)setWin:(NSString*)win andLose:(NSString*)lose andFirstWon:(BOOL)yn{
    winView.hidden = NO;
    [winLabel setText:[NSString stringWithFormat:@" WIN %@ ",win]];
    [winLabel setFont:[UIFont fontWithName:@"Verdana-BoldItalic" size:10]];
    [winLabel setTextColor:ColorFromRGB(0xffffff)];
    [winLabel setColorWord:@"WIN" withColor:ColorFromRGB(0x55bcfd)];
    [winLabel sizeToFit];
    
    [loseLabel setText:[NSString stringWithFormat:@" LOSE %@ ",lose]];
    [loseLabel setFont:[UIFont fontWithName:@"Verdana-BoldItalic" size:10]];
    [loseLabel setTextColor:ColorFromRGB(0xffffff)];
    [loseLabel setColorWord:@"LOSE" withColor:ColorFromRGB(0xd74040)];
    [loseLabel sizeToFit];
    
    float width = (winLabel.frame.size.width > loseLabel.frame.size.width) ? winLabel.frame.size.width : loseLabel.frame.size.width;
    width = (width > winImageView.frame.size.width) ? width : winImageView.frame.size.width;
    
    winImageView.frame = yn ? CGRectMake(0, 0, 61, 54) : CGRectMake(width-61, 0, 61, 54);
    winLabel.frame = yn ? CGRectMake(0, winImageView.frame.origin.y+winImageView.frame.size.height+5, winLabel.frame.size.width, winLabel.frame.size.height) : CGRectMake(width-winLabel.frame.size.width, winImageView.frame.origin.y+winImageView.frame.size.height+5, winLabel.frame.size.width, winLabel.frame.size.height);
    loseLabel.frame = yn ? CGRectMake(0, winLabel.frame.origin.y+winLabel.frame.size.height+2, loseLabel.frame.size.width, winLabel.frame.size.height) : CGRectMake(width-loseLabel.frame.size.width, winLabel.frame.origin.y+winLabel.frame.size.height+2, loseLabel.frame.size.width, winLabel.frame.size.height);
    
    float height = loseLabel.frame.origin.y+loseLabel.frame.size.height;
    winView.frame = yn ? CGRectMake(10, firstSelect.center.y+30, width, height) : CGRectMake(mySize.width-10-width, secondSelect.center.y+30, width, height);
    
    [self winAnimationScale];
    
}

#pragma mark - WIN 애니메이션

-(void)winAnimationScale{
    
    winImageView.alpha = 1.0f;
    CABasicAnimation *pulseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    pulseAnimation.duration = 1;
    pulseAnimation.toValue = [NSNumber numberWithFloat:2];
    pulseAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
//    pulseAnimation.autoreverses = YES;
    [winImageView.layer addAnimation:pulseAnimation forKey:@"scale"];
    
    [UIView animateWithDuration:1.0f animations:^{
        winImageView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        winImageView.alpha = 1.0f;
        [self winAnimationStart];
    }];
    

}

-(void)winAnimationStart{
    
    
    CABasicAnimation *pulseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    pulseAnimation.duration = .5;
    pulseAnimation.toValue = [NSNumber numberWithFloat:1.1];
    pulseAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pulseAnimation.autoreverses = YES;
    pulseAnimation.repeatCount = FLT_MAX;
    
    [winImageView.layer addAnimation:pulseAnimation forKey:@"pitapat"];
}

-(void)winAnimationStop{
    
    [winImageView.layer removeAnimationForKey:@"pitapat"];
    
}


#pragma mark - 아이콘 애니메이션
//vs
-(void)iconAnimation:(UIImageView*)targetImage{
    
    CGRect rect = CGRectMake(0, 0, targetImage.frame.size.width, targetImage.frame.size.height);
    rect = CGRectInset(rect, 2, 2);
    
    float r = rect.size.width*0.5f;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(r, r*2)];
    
    for (int i = 1; i<=40; i++) {
        
        CGPoint tPoint = CGPointMake(r+(r*sinl((i/(M_PI*2)))), r+(r*cosl((i/(M_PI*2)))));
        [path addLineToPoint:tPoint];
    }
    
    centerIconPathLayer = [CAShapeLayer layer];
    centerIconPathLayer.frame = rect;
    centerIconPathLayer.geometryFlipped = YES;
    centerIconPathLayer.path = path.CGPath;
    centerIconPathLayer.strokeColor = ColorFromRGB(0xfff200).CGColor;
    centerIconPathLayer.fillColor = nil;
    centerIconPathLayer.lineWidth = 4.0f;
    centerIconPathLayer.lineJoin = kCALineJoinBevel;
    
    [targetImage.layer addSublayer:centerIconPathLayer];
    
    [self startIconAnimation];
}

-(void)startIconAnimation{
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 3.0;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.repeatCount = 1;
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    [centerIconPathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
}

//loading
-(void)loadingIconAnimation:(UIImageView*)targetImage{
    
    CGRect rect = CGRectMake(0, 0, targetImage.frame.size.width, targetImage.frame.size.height);
    rect = CGRectInset(rect, 8, 8);
    
    float r = rect.size.width*0.5f;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(r, r*2)];
    
    for (int i = 1; i<=40; i++) {
        
        CGPoint tPoint = CGPointMake(r+(r*sinl((i/(M_PI*2)))), r+(r*cosl((i/(M_PI*2)))));
        [path addLineToPoint:tPoint];
    }
    
    CAShapeLayer *pathLayer = [CAShapeLayer layer];
    pathLayer.frame = rect;
    pathLayer.geometryFlipped = YES;
    pathLayer.path = path.CGPath;
    pathLayer.strokeColor = ColorFromRGB(0xfff200).CGColor;
    pathLayer.fillColor = nil;
    pathLayer.lineWidth = 1.5f;
    pathLayer.lineJoin = kCALineJoinBevel;
    
    [targetImage.layer addSublayer:pathLayer];
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 2.0;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.repeatCount = HUGE_VALF;
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    [pathLayer addAnimation:pathAnimation forKey:@"loadingIconAnimation"];
}

#pragma mark - 뒤로
-(void)backButtonAction:(id)sender{
    
    [self stopToLoadingTime];
    [appDelegate removeActivity];
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController removeBattlingView];
}

#pragma mark - 선택
-(void)firstSelectAction:(id)sender{
    
    
    //맨처음 호출할때
//    mGender = (currentLoadingIndex == 1) ? [[self.firstDic objectForKey:@"gender"] integerValue] : 0;
    
    firstSelect.enabled = secondSelect.enabled = NO;
    firstWon = YES;
    
    if (checkFirst) {
        //맨처음 호출
        mGender = [[self.firstDic objectForKey:@"gender"] integerValue];
        [self requestTotalListAtGender:mGender];
    }else{
        mGender = 0;
        
        firstSelect.layer.borderColor = ColorFromRGB(0x49a1d9).CGColor;
        firstSelect.layer.borderWidth = 2.0f;
        secondSelect.layer.borderWidth = 0.0f;
        [self requestClickWithWinner:[self.firstDic objectForKey:@"star_id"] andLoser:[self.secondDic objectForKey:@"star_id"]];
    }
    
    //임시
//    NSString *genderStr = [self.firstDic objectForKey:@"gender"];
//    if (genderStr) {
//        if ([genderStr isEqualToString:@"m"]) {
//            mGender = 1;
//        }else if([genderStr isEqualToString:@"f"]){
//            mGender = 2;
//        }
//    }
    
    
    
}

-(void)secondSelectAction:(id)sender{
    
//    [self removeFirstSelect];
//    mGender = (currentLoadingIndex == 1) ? [[self.secondDic objectForKey:@"gender"] integerValue] : 0;
    
    //임시
//    NSString *genderStr = [self.secondDic objectForKey:@"gender"];
//    if (genderStr) {
//        if ([genderStr isEqualToString:@"m"]) {
//            mGender = 1;
//        }else if([genderStr isEqualToString:@"f"]){
//            mGender = 2;
//        }
//    }
    
    firstWon = NO;
    firstSelect.enabled = secondSelect.enabled = NO;
    
    if (checkFirst) {
        mGender = [[self.secondDic objectForKey:@"gender"] integerValue];
        [self requestTotalListAtGender:mGender];
    }else{
        mGender = 0;
        
        secondSelect.layer.borderWidth = 2.0f;
        secondSelect.layer.borderColor = ColorFromRGB(0x49a1d9).CGColor;
        firstSelect.layer.borderWidth = 0.0f;
        [self requestClickWithWinner:[self.secondDic objectForKey:@"star_id"] andLoser:[self.firstDic objectForKey:@"star_id"]];
    }
    
    
    
    
}

#pragma mark - 기사보기
-(void)firstNewsButtonAction:(id)sender{
    
    ViewController *vController = (ViewController*)appDelegate.window.rootViewController;
    
    NewsViewController *news = [[NewsViewController alloc] init];
    
    NSString *title = [self.firstDic objectForKey:@"name"];
    NSURL *url = [NSURL URLWithString:[self.firstDic objectForKey:@"news_url"]];
    
    [news setNewsTitle:title andURL:url];
    
    [vController presentModalViewController:news animated:YES];
}

-(void)secondNewsButtonAction:(id)sender{
    
    ViewController *vController = (ViewController*)appDelegate.window.rootViewController;
    NewsViewController *news = [[NewsViewController alloc] init];
    
    NSString *title = [self.secondDic objectForKey:@"name"];
    NSURL *url = [NSURL URLWithString:[self.secondDic objectForKey:@"news_url"]];
    
    [news setNewsTitle:title andURL:url];
    [vController presentModalViewController:news animated:YES];
}



#pragma mark - 애니메이션
-(void)appearSelectButtonAnimation{
    if (!loadingTimer) {
        
        [self removeLoadingView];
    }
    firstSelect.hidden = secondSelect.hidden = NO;
    [UIView animateWithDuration:0.3f animations:^{
        firstSelect.frame = CGRectMake(FIRSTSELECT_APPEAR_X, firstSelect.frame.origin.y, firstSelect.frame.size.width, firstSelect.frame.size.height);
        secondSelect.frame = CGRectMake(SECONDSELECT_APPEAR_X, secondSelect.frame.origin.y, secondSelect.frame.size.width, secondSelect.frame.size.height);
    } completion:^(BOOL finished) {
        
    }];
}

-(void)removeFirstSelect{
    
//    firstSelect.hidden = YES;
//    firstImageView.image = nil;
//    firstSelect.frame = CGRectMake(FIRSTSELECT_HIDDEN_X, firstSelect.frame.origin.y, firstSelect.frame.size.width, firstSelect.frame.size.height);
//    [self appearSmallLoadingViewOnLeft:YES];
//    return;

    
    firstDic = nil;
    [self animationEffectRottion:firstSelect.layer andDurationTime:NEXTDELAYTIME];
    NSLog(@"tenArray count : %d",self.tenArray.count);

    //sel.tenarray.count가 0보다 큰지 안큰지 비교해서 만약 크면 effectAnimationComplete:의 nextBattleStart함수 호출 못하게 하자
    [NSTimer scheduledTimerWithTimeInterval:NEXTDELAYTIME-0.1f target:self selector:@selector(effectAnimationComplete:) userInfo:[NSNumber numberWithInteger:1] repeats:NO];
    
}

-(void)removeSecondSelect{
    
//    secondSelect.hidden = YES;
//    secondImageView.image = nil;
//    secondSelect.frame = CGRectMake(SECONDSELECT_HIDDEN_X, secondSelect.frame.origin.y, secondSelect.frame.size.width, secondSelect.frame.size.height);
//    [self appearSmallLoadingViewOnLeft:NO];
//    return;

    
    secondDic = nil;
    [self animationEffectRottion:secondSelect.layer andDurationTime:NEXTDELAYTIME];
    NSLog(@"tenArray count 2 : %d",self.tenArray.count);
    [NSTimer scheduledTimerWithTimeInterval:NEXTDELAYTIME-0.1f target:self selector:@selector(effectAnimationComplete:) userInfo:[NSNumber numberWithInteger:2] repeats:NO];

}

-(void)effectAnimationComplete:(NSTimer*)timer{
    NSInteger index = (NSInteger)[timer.userInfo integerValue];
    if (index == 1) {
        
        firstSelect.hidden = YES;
        firstImageView.image = nil;
        firstDic = nil;
        firstSelect.frame = CGRectMake(FIRSTSELECT_HIDDEN_X, firstSelect.frame.origin.y, firstSelect.frame.size.width, firstSelect.frame.size.height);
        [self appearSmallLoadingViewOnLeft:YES];
    }else{
        
        secondSelect.hidden = YES;
        secondImageView.image = nil;
        secondDic = nil;
        secondSelect.frame = CGRectMake(SECONDSELECT_HIDDEN_X, secondSelect.frame.origin.y, secondSelect.frame.size.width, secondSelect.frame.size.height);
        [self appearSmallLoadingViewOnLeft:NO];
    }
//    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(nextBattleStart) userInfo:nil repeats:NO];  //다음 배틀시작
    [self nextBattleStart];
}

-(void)animationEffectRottion:(CALayer*)targetLayer andDurationTime:(CFTimeInterval)dTime{
    
	CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
	rotationAnimation.toValue = [NSNumber numberWithFloat:(2 * M_PI) * 3]; // 3 is the number of 360 degree rotations
    // Make the rotation animation duration slightly less than the other animations to give it the feel
    // that it pauses at its largest scale value
	rotationAnimation.duration = dTime;
	rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
	
	CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
	scaleAnimation.fromValue = [NSNumber numberWithFloat:1.0];
	scaleAnimation.toValue = [NSNumber numberWithFloat:0.0];
	scaleAnimation.duration = dTime;
	scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
	
	CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
	animationGroup.duration = dTime;
	animationGroup.autoreverses = NO;
	animationGroup.repeatCount = 1;
	[animationGroup setAnimations:[NSArray arrayWithObjects:rotationAnimation, scaleAnimation, nil]];
    
    [targetLayer addAnimation:animationGroup forKey:@"animationGroup"];

}

#pragma mark - 이미지
-(void)imageSetting{
    
    [imageTenDic removeAllObjects];
    [imageTenArray removeAllObjects];
    
    for (int i = 0; i<[self.tenArray count]; i++) {
        NSString *imgString = [[self.tenArray objectAtIndex:i] objectForKey:@"photo_url"];
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:imgString imageBlock:^(UIImage *image) {
            
            UIImage *_img = [self cropByImage:image andSize:firstImageView.frame.size];
            
            [imageTenDic setValue:UIImageJPEGRepresentation(_img, 0.5f) forKey:imgString];
            
            [imageTenArray addObject:imgString];
            
            NSLog(@"딕셔너리저장");
            if ([imageTenArray count] == [self.tenArray count]) {
                [self imageLoadComplete];
            }

        } errorBlock:^{
            [imageTenArray addObject:imgString];
            NSLog(@"딕셔너리저장 실패");
            if ([imageTenArray count] == [self.tenArray count]) {
                [self imageLoadComplete];
            }
        }];
    }
    
}

-(void)imageLoadComplete{
    
    NSLog(@"---이미지 저장 완료----");
//    if (!loadingTimer) {
//        
//        [self removeLoadingView];
//    }
    //데이타 집어넣고 드뎌배팅시작
    
    if (checkFirst && [self.tenArray count] >= 2) {
        [self settingFirstBattleObject:[self.tenArray objectAtIndex:0] andObject:[self.tenArray objectAtIndex:1]];
    }else{
                [self settingCurrentTurnObject:[self.tenArray objectAtIndex:0]];
    }

    checkFirst = NO;

}

#pragma mark - 오브젝트 적용
-(void)settingFirstObject:(NSDictionary*)dic{
    
    self.firstDic = dic;
    
    firstTitle.text = [dic objectForKey:@"name"];

    if (imageTenArray.count > 0) {
        
        NSString *keyStr = [dic objectForKey:@"photo_url"];
        
        if ([imageTenDic objectForKey:keyStr]) {
            UIImage *image = [UIImage imageWithData:[imageTenDic objectForKey:keyStr]];
            firstImageView.image = image;
            [self appearSelectButtonAnimation];
        }else{
            //다음이미지
            [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:keyStr imageBlock:^(UIImage *image) {
                firstImageView.image = image;
                [self appearSelectButtonAnimation];
            } errorBlock:^{
                
                [self appearSelectButtonAnimation];
            }];
//            NSDictionary *dic = [self.tenArray objectAtIndex:0];
//            [self settingCurrentTurnObject:dic];
            
        }
    }else{
        
        
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[dic objectForKey:@"photo_url"] imageBlock:^(UIImage *image) {
            firstImageView.image = [self cropByImage:image andSize:firstImageView.frame.size];
            
            if (firstImageView.image) {
                [self appearSelectButtonAnimation];
            }
            
        } errorBlock:^{
            firstImageView.image = nil;
        }];
    }
    
    
}

-(void)settingSecondObject:(NSDictionary*)dic{
    
    self.secondDic = dic;
    secondTitle.text = [dic objectForKey:@"name"];
    
    
    if (imageTenArray.count > 0) {
        NSString *keyStr = [dic objectForKey:@"photo_url"];
        
        if ([imageTenDic objectForKey:keyStr]) {
            UIImage *image = [UIImage imageWithData:[imageTenDic objectForKey:keyStr]];
            secondImageView.image = image;
            [self appearSelectButtonAnimation];
        }else{
            //다음이미지
//            NSDictionary *dic = [self.tenArray objectAtIndex:0];
//            [self settingCurrentTurnObject:dic];
            
            [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:keyStr imageBlock:^(UIImage *image) {
                secondImageView.image = image;
                [self appearSelectButtonAnimation];
            } errorBlock:^{
                
                [self appearSelectButtonAnimation];
            }];
            
        }
    }else{
        
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:[dic objectForKey:@"photo_url"] imageBlock:^(UIImage *image) {
            secondImageView.image = [self cropByImage:image andSize:firstImageView.frame.size];
            
            if (secondImageView.image) {
                [self appearSelectButtonAnimation];
            }
            
        } errorBlock:^{
            secondImageView.image = nil;
        }];
    }
    
    
}



//이번차례 딕셔너리적용
-(void)settingCurrentTurnObject:(NSDictionary*)dic{
    
    NSLog(@"이번 차례 : %@",[dic objectForKey:@"name"]);
    
    if (firstSelect.enabled == YES) {
        //로딩끝난후 한번만 들어와야 하므로
        NSLog(@"settingCurrentTurnObject");
//        return;
    }
    
    firstSelect.enabled = secondSelect.enabled = YES;
    //셀렉박스가 비어있는지 확인후 넣음
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_BATTLE Label:ANA_LAB_Battle_Second];
    
    
    
    if (!self.firstDic) {
        [self settingFirstObject:dic];
    }else{
        [self settingSecondObject:dic];
    }
    
    [self.tenArray removeObjectAtIndex:0];  //쓴거 지움
    [self removeSmallLoadingView];
    [self startIconAnimation];
    
    //맨리로드
    if (languagesKorean) {
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController requestManSDK];
    }

    
}

//첫번째 배틀 시작
-(void)settingFirstBattleObject:(NSDictionary*)fDic andObject:(NSDictionary*)sDic{
    
    firstSelect.enabled = secondSelect.enabled = YES;
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_BATTLE Label:ANA_LAB_Battle_Second]; //애널리틱스
    
    [self settingFirstObject:fDic];
    [self settingSecondObject:sDic];
    
    //쓴거 지우고
    [self.tenArray removeObjectAtIndex:0];
    [self.tenArray removeObjectAtIndex:0];
    
    [self startIconAnimation];  //동그라미
    
    //맨리로드
    if (languagesKorean) {
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        [viewController requestManSDK];
    }
    
}

-(UIImage*)cropByImage:(UIImage*)image andSize:(CGSize)size{
    
    
    //세로맞춘다음 비율에 맞게 이미지 자름
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    
    float wid = (size.width*imageHeight)/size.height;
    float x = (imageWidth*0.5)-(wid*0.5f);
    
    
   
    //예외처리
    x = (x<0) ? 0:x;
    wid = (wid > imageWidth) ? imageWidth : wid;
    
    CGRect rect = CGRectMake(x, 0, wid, imageHeight);
    
    //인제알맞게 자르자
    CGImageRef imageREF = CGImageCreateWithImageInRect(image.CGImage, rect);
    UIImage *cropped = [UIImage imageWithCGImage:imageREF];
    CGImageRelease(imageREF);
    
    
    return cropped;
    
}


#pragma mark - 리스트관련
-(NSArray*)settingTenArrayOnFirst:(BOOL)yn{
    
    NSLog(@"settingTenArrayOnFirst");
    NSMutableArray *tArray = [[NSMutableArray alloc] init];
    while ([tArray count] < appDelegate.battleAdCount && [self.totalArray count] > 0) {
        NSDictionary *dic = [self.totalArray objectAtIndex:0];
        [tArray addObject:dic];
        [self.totalArray removeObjectAtIndex:0];
    }
    
    if (yn) {
        //11위부터 믹스
//        [self shuffle];   //서버에서랜덤해줌 고로쓸필요없음
        
    }
    
    return tArray;
}

- (void)shuffle
{
    NSUInteger count = [self.totalArray count];
    for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        NSInteger nElements = count - i;
        NSInteger n = arc4random_uniform(nElements) + i;
        [self.totalArray exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
    
    
}

-(NSString*)loadTenStars:(NSArray*)array{
    
    NSString *string = @"";
    
    for (int i = 0; i<[array count]; i++) {
        if (i == 0) {
            
            string = [string stringByAppendingString:[[array objectAtIndex:i] objectForKey:@"star_id"]];
        }else{
            
            string = [string stringByAppendingString:[NSString stringWithFormat:@"_%@",[[array objectAtIndex:i] objectForKey:@"star_id"]]];
        }
    }
    return string;
    
}


#pragma mark - 시작
-(void)nextBattleStart{
    winView.hidden = YES;
    firstSelect.layer.borderWidth = secondSelect.layer.borderWidth = 0.0f;
    
    if ([self.tenArray count] > 0) {
        NSDictionary *dic = [self.tenArray objectAtIndex:0];
        [self settingCurrentTurnObject:dic];

    }else{
        if ([self.totalArray count] <= 0) {
            //마지막배틀까지 다하면 다시1위부터 부름
            [self.totalArray setArray:self.rankingArray];
        }
        NSArray *tArray = [self settingTenArrayOnFirst:NO];    //스타`1~10위 추출 및 나머진 섞기
        NSString *starIds = [self loadTenStars:tArray];         //스타아이디 스트링으로 뽑아내고
        [self requestStarIDs:starIds];                          //배틀돌릴 스타10명정보(배틀리스트) 요청
    }

}

#pragma mark - 로딩

-(void)makeLoadingView{
    
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    
    loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];
    loadingView.backgroundColor = [UIColor clearColor];
    [viewController.view addSubview:loadingView];
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, loadingView.frame.size.width, loadingView.frame.size.height)];
    bgView.backgroundColor = ColorFromRGB(0x413c43);
    bgView.alpha = 0.95f;
    [loadingView addSubview:bgView];
    
    float originY = deviceIphone4 ? 15 : 62;
    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, originY, 39, 39)];
    icon.image = [UIImage imageNamed:@"loading_circle"];
    [loadingView addSubview:icon];
    icon.center = CGPointMake(mySize.width*0.5f, icon.center.y);
    [self loadingIconAnimation:icon];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.frame.origin.y+icon.frame.size.height, mySize.width, 50)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.text = [NSString stringWithFormat:@"%@\n%@",NSLocalizedString(@"loadingBattle1", @""),NSLocalizedString(@"loadingBattle2", @"")];
    titleLabel.numberOfLines = 0;
    titleLabel.font = [UIFont systemFontOfSize:13];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = ColorFromRGB(0xffffff);
    [loadingView addSubview:titleLabel];
    
    originY = deviceIphone4 ? loadingView.frame.size.height-20-350 : loadingView.frame.size.height-60-350;
    UIView *adView = [[UIView alloc] initWithFrame:CGRectMake(0, originY, 219, 350)];
    [loadingView addSubview:adView];
    adView.center = CGPointMake(mySize.width*0.5f, adView.center.y);
    adView.backgroundColor = ColorFromRGB(0xffffff);
    
	
    manBreakAdView = [[ManBreakAdView alloc] initWithFrame:CGRectMake(0, 0, adView.frame.size.width, adView.frame.size.height)];
    manBreakAdView.delegate = self;
    [manBreakAdView applicationID:@"dispatch/dispatch/" adWindowId:@"flexible"];
    [adView addSubview:manBreakAdView];
    [manBreakAdView startBreakAd];
    
    UIButton *xbutton = [[UIButton alloc] initWithFrame:CGRectMake(loadingView.frame.size.width-5-41, myOrginY+5, 41, 51)];
    [xbutton setImage:[UIImage imageNamed:@"btn_close"] forState:UIControlStateNormal];
    [xbutton addTarget:self action:@selector(removeLoadingView) forControlEvents:UIControlEventTouchUpInside];
    [loadingView addSubview:xbutton];
}



-(void)apearLoadingView{
    if (!loadingView) {
        [self makeLoadingView];
    }
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    [viewController.view bringSubviewToFront:loadingView];
    
    loadingView.hidden = NO;

    [manBreakAdView startBreakAd];
    
    [self stopToLoadingTime];
    loadingTimer = [NSTimer scheduledTimerWithTimeInterval:appDelegate.battleAdTime target:self selector:@selector(loadingViewTimerAction) userInfo:nil repeats:NO];
    
}

-(void)removeLoadingView{
    
    [self stopToLoadingTime];
    loadingView.hidden = YES;
}

-(void)loadingViewTimerAction{
    
    [self stopToLoadingTime];
    if ([imageTenArray count] >= [self.tenArray count]) {
        [self removeLoadingView];
    }
}

-(void)stopToLoadingTime{
    
    if (loadingTimer) {
        [loadingTimer invalidate];
        loadingTimer = nil;
    }
}

#pragma mark delegate
- (void)didClickBreakAd{
//    [self removeLoadingView];
}



#pragma mark - 네트워크
-(void)requestStart{
    //배틀준비
    
    currentLoadingIndex = 1;
    NSString *dataStr = [NSString stringWithFormat:@"lang=%@",appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];

    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_BATTLE_READY,dataStr];
    [self requestURL:url];
}

-(void)requestClickWithWinner:(NSString*)winner andLoser:(NSString*)loser{
    
    if (mGender > 0) {
        
        currentLoadingIndex = 2;
    }
    NSString *dataStr = [NSString stringWithFormat:@"winner_id=%@&loser_id=%@&deviceid=%@&lang=%@",winner,loser,[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_BATTLE_CLICK,dataStr];
    [self requestURL:url];
}


-(void)requestTotalListAtGender:(NSInteger)gen{

    currentLoadingIndex = 3;
    NSString *dataStr = [NSString stringWithFormat:@"gender=%d&lang=%@",gen,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_BATTLE_TOTAL_LIST,dataStr];
    [self requestURL:url];
}

-(void)requestStarIDs:(NSString*)starIDs{
    currentLoadingIndex = 4;
    self.currentStarIDs = starIDs;
    NSString *dataStr = [NSString stringWithFormat:@"star_id=%@&lang=%@",starIDs,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_BATTLE_LIST,dataStr];
    [self requestURL:url];
    [self apearLoadingView];
}

-(void)requestURL:(NSString*)url{
    
    [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"배틀리스트 네트워크 요청 : %@",url);
            }
            
            //api나오면 여기에 작업
            
            
        }
    }
}




#pragma mark delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    duringNetwork = NO;

    
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    NSString *currentRequestString = [NSString stringWithFormat:@"%@",connectio.currentRequest];
    
    NSLog(@"무한배틀 : %@",resultDictionary);
    
    if ([currentRequestString rangeOfString:URL_BATTLE_READY].location != NSNotFound) {
        //배틀준비
        
        self.imageURL = ([appDelegate checkObject:[resultDictionary objectForKey:@"imgurl"]]) ? [resultDictionary objectForKey:@"imgurl"] : nil;
        self.subTitleLabel.text = ([appDelegate checkObject:[resultDictionary objectForKey:@"title"]]) ? [resultDictionary objectForKey:@"title"] : nil;
        
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0) {
                self.itemArray = [[resultDictionary objectForKey:@"data"] objectForKey:@"items"];
                [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_BATTLE Label:ANA_LAB_Battle_First];
                [self settingFirstObject:[self.itemArray objectAtIndex:0]];
                [self settingSecondObject:[self.itemArray objectAtIndex:1]];
                checkFirst = YES;
                
            }
        }
    }else if([currentRequestString rangeOfString:URL_BATTLE_CLICK].location != NSNotFound){
        //클릭함
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0) {
                NSLog(@"클릭 : %@",resultDictionary);
                
                NSString *win = [[resultDictionary objectForKey:@"data"] objectForKey:@"win_cnt"];
                NSString *lose = [[resultDictionary objectForKey:@"data"] objectForKey:@"lose_cnt"];
                
                [self setWin:win andLose:lose andFirstWon:firstWon];    //하트띄우기
                if (firstWon) {
                    [self removeSecondSelect];
                }else{
                    
                    [self removeFirstSelect];
                }
            }
        }
    }else if([currentRequestString rangeOfString:URL_BATTLE_TOTAL_LIST].location != NSNotFound){
        //배틀 총 리스트
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                
                NSArray *array = [[resultDictionary objectForKey:@"data"] objectForKey:@"items"];
                [self.totalArray setArray:array];
                
//                NSLog(@"총 리스트");
//                for (int i = 0; i<[self.totalArray count]; i++) {
//                    
//                    NSString *string = [[self.totalArray objectAtIndex:i] objectForKey:@""]
//                }
                
                self.rankingArray = [NSArray arrayWithArray:array];
                
                //첫번째 셀렉 비움
                firstImageView.image = nil;
                firstDic = nil;
                firstSelect.frame = CGRectMake(FIRSTSELECT_HIDDEN_X, firstSelect.frame.origin.y, firstSelect.frame.size.width, firstSelect.frame.size.height);
                
                //두번째 셀렉 비움
                secondImageView.image = nil;
                secondDic = nil;
                secondSelect.frame = CGRectMake(SECONDSELECT_HIDDEN_X, secondSelect.frame.origin.y, secondSelect.frame.size.width, secondSelect.frame.size.height);

            
                NSArray *tArray = [self settingTenArrayOnFirst:YES];    //스타`1~?위 추출
                NSString *starIds = [self loadTenStars:tArray];         //스타아이디 스트링으로 뽑아내고
                [self requestStarIDs:starIds];                          //배틀돌릴 스타10명정보(배틀리스트) 요청
            }
        }
        
    }else if([currentRequestString rangeOfString:URL_BATTLE_LIST].location != NSNotFound){
        //배틀리스트 10개 뽑아옴
        winView.hidden = YES;
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                
                
                [self.tenArray removeAllObjects];
                
                NSArray *array = [[resultDictionary objectForKey:@"data"] objectForKey:@"items"];

                [self.tenArray addObjectsFromArray:array];
                
                NSLog(@"이번에 부른 데이타");
                for (int i = 0; i<self.tenArray.count; i++) {
                    NSDictionary *dic = [self.tenArray objectAtIndex:i];
                    NSLog(@"%d : %@",i,[dic objectForKey:@"name"]);
                }
                
                if (!nofirstLoading) {
                    //1위는 사용안하기 땜에 지워야함
                    if (self.tenArray.count > 0) {
                        
//                        [self.tenArray removeObjectAtIndex:0];
                    }
                }
                
                //이미지 10개씩 로컬저장
                [self imageSetting];
                
            }
        }
    }
    
    
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
    [self removeLoadingView];
    firstSelect.enabled = secondSelect.enabled = YES;
    
    NSString *currentRequestString = [NSString stringWithFormat:@"%@",connection.currentRequest];
    if ([currentRequestString rangeOfString:URL_BATTLE_READY].location != NSNotFound) {
        //배틀준비
        NSLog(@"배틀준비 요청 실패 : %@",error);
        [appDelegate alertViewWithMessage:NSLocalizedString(@"Failed to load", @"") andTimeInterval:2.0f];
        [self backButtonAction:nil];
        
    }else if([currentRequestString rangeOfString:URL_BATTLE_CLICK].location != NSNotFound){
        //클릭함
        NSLog(@"배틀클릭 요청 실패 : %@",error);
        [[PopupView getPopupViewWithDelegate:self] appearMessage:NSLocalizedString(@"Failed to load", @"")
                                                 withFirstButton:NSLocalizedString(@"Close",@"Close")
                                                 andSecondButton:NSLocalizedString(@"Try again",@"Try again") andTag:1];
        
    }else if([currentRequestString rangeOfString:URL_BATTLE_TOTAL_LIST].location != NSNotFound){
        //배틀 총 리스트
        NSLog(@"배틀총리스트 요청 실패 : %@",error);
        [appDelegate alertViewWithMessage:NSLocalizedString(@"Failed to load", @"") andTimeInterval:2.0f];
        [self backButtonAction:nil];
        
    }else if([currentRequestString rangeOfString:URL_BATTLE_LIST].location != NSNotFound){
        //배틀리스트 10개 뽑아옴
        NSLog(@"배틀리스트 (10개) 요청 실패 : %@",error);
        [[PopupView getPopupViewWithDelegate:self] appearMessage:NSLocalizedString(@"Failed to load", @"")
                                                 withFirstButton:NSLocalizedString(@"Close",@"Close")
                                                 andSecondButton:NSLocalizedString(@"Ok",@"Ok") andTag:2];
    }

}

#pragma mark - popup

-(void)popupView:(PopupView *)popupView clickIndex:(NSInteger)index{
    
    if (popupView.tag == 1) {
        //배틀클릭 요청 실패
        if (index == 1) {
            //재시도
            [self requestClickWithWinner:[self.firstDic objectForKey:@"star_id"] andLoser:[self.secondDic objectForKey:@"star_id"]];
        }
    }else if(popupView.tag == 2){
        //배틀클릭 10개 실패
        if (index == 1) {
            //재시도
            [self requestStarIDs:currentStarIDs];
        }
    }
}



@end
